<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Education
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
class Education_IndexController extends Core_Controller_Action_Standard
{
  protected $_navigation;

  public function init()
  {
    if( !$this->_helper->requireAuth()->setAuthParams('education', null, 'view')->isValid() ) return;
    
    if( !Engine_Api::_()->core()->hasSubject() )
    {
      if( 0 !== ($education_id = (int) $this->_getParam('education_id')) &&
          null !== ($education = Engine_Api::_()->getItem('education', $education_id)) )
      {
        Engine_Api::_()->core()->setSubject($education);
      }
      else if( 0 !== ($user_id = (int) $this->_getParam('user_id')) &&
          null !== ($user = Engine_Api::_()->getItem('user', $user_id)) )
      {
        Engine_Api::_()->core()->setSubject($user);
      }
    }
    
    $this->_helper->requireUser->addActionRequires(array(
      'create',
      'delete',
      'edit',
      'manage',
    ));

    $this->_helper->requireSubject->setActionRequireTypes(array(
      'delete' => 'education',
      'edit' => 'education',
      'view' => 'education',
      'list' => 'user',
    ));
  }
  
  
  public function indexAction()
  {
    $this->_helper->content->setNoRender()->setEnabled();
  }
  
  // NONE USER SPECIFIC METHODS
  public function browseAction()
  {

    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->form = $form = new Education_Form_Search();
    $form->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action'=>'browse'),'education_general',true));

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }
    
    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    $this->view->formValues = $values;
            
    $this->view->assign($values);

    if (!empty($values['tag']))
    {
      $this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
    }    
    
    if (!empty($values['category']))
    {
      //$this->view->categoryObject = Engine_Api::_()->education()->getCategory($values['category']);  
    }
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('education.perpage', 10);
    $this->view->paginator = $paginator = Engine_Api::_()->education()->getEducationsPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    
    
    // Render
    $this->_helper->content
      //  ->setNoRender()
        ->setEnabled()
        ;    
    
  }

  
  public function manageAction()
  {
    // Get navigation
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_main');

    // Get quick navigation
    $this->view->quickNavigation = $quickNavigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_quick'); 
    
    
    $viewer = Engine_Api::_()->user()->getViewer();

    $this->view->form = $form = new Education_Form_Search();
    $form->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action'=>'manage'),'education_general',true));
    

    $values = array();
    // Populate form data
    if( $form->isValid($this->_getAllParams()) )
    {
      $values = $form->getValues();
    }

    $values = Engine_Api::_()->getApi('filter','radcodes')->removeKeyEmptyValues($values);
    $this->view->formValues = $values;
            
    $this->view->assign($values);
          
    if (!empty($values['tag']))
    {
      $this->view->tagObject = Engine_Api::_()->getItem('core_tag', $values['tag']);
    }    
    
    if (!empty($values['category']))
    {
      //$this->view->categoryObject = Engine_Api::_()->education()->getCategory($values['category']);  
    }    
    
    $values['limit'] = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('education.perpage', 10);
    $values['user'] = $viewer;
    $this->view->paginator = $paginator = Engine_Api::_()->education()->getEducationsPaginator($values);
    $paginator->setCurrentPageNumber($this->_getParam('page', 1));    

    $this->view->can_create = Engine_Api::_()->authorization()->isAllowed('education', $viewer, 'create');
  }


  public function listAction()
  {
    // Get navigation
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_main');

    $this->view->owner = $owner = Engine_Api::_()->core()->getSubject('user');  
      
    $values = array();
    $values['user'] = $owner;
    $values['order'] = Engine_Api::_()->getApi('settings', 'core')->getSetting('education.listorder', 'year');
    $this->view->paginator = $paginator = Engine_Api::_()->education()->getEducationsPaginator($values);    
       
  }
  
  
  public function viewAction()
  {
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->education = $education = Engine_Api::_()->core()->getSubject('education');

    // Check auth
    if (!$this->_helper->requireAuth()->setAuthParams($education, null, 'view')->isValid() ) {
      return;
    }
    
    if (!$education->isOwner($viewer)) 
    {
      $education->view_count++;
      $education->save();
    }
    
    $this->view->owner = $education->getOwner();
    
    // get tags
    $this->view->educationTags = $education->tags()->getTagMaps();
    
    $this->view->addHelperPath(APPLICATION_PATH . '/application/modules/Fields/View/Helper', 'Fields_View_Helper');
    $this->view->fieldStructure = $fieldStructure = Engine_Api::_()->fields()->getFieldsStructurePartial($education); 
    
    // Get navigation
    $this->view->gutterNavigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_gutter');
    
    $this->view->totalEducations = Engine_Api::_()->education()->countEducations(array('user'=>$education->user_id));
  }

    
  
  
  public function createAction()
  {
    if( !$this->_helper->requireAuth()->setAuthParams('education', null, 'create')->isValid()) return;
    
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('education_main');
    
    $this->view->form = $form = new Education_Form_Create();
    
    if (!$this->getRequest()->isPost())
    {
      return;
    }
    
    if (!$form->isValid($this->getRequest()->getPost()))
    {
      return;
    }
    
    
    $table = Engine_Api::_()->getItemTable('education');
    $db = $table->getAdapter();
    $db->beginTransaction();

    try
    {   	
      $values = $form->getValues();
      $values['user_id'] = $viewer->getIdentity();
      $values['featured'] = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'review', 'featured') ? 1 : 0;
      
      
      $education = $table->createRow();
      $education->setFromArray($values);
      $education->save();

      // Add tags
      $tags = preg_split('/[,]+/', $values['keywords']);
      $tags = array_filter(array_map("trim", $tags));
      $education->tags()->addTagMaps($viewer, $tags);

      $customfieldform = $form->getSubForm('customField');
      $customfieldform->setItem($education);
      $customfieldform->saveValues();

      // Set photo
      if( !empty($values['photo']) ) 
      {
        $education->setPhoto($form->photo);
      }      
      
      // CREATE AUTH STUFF HERE
      $auth = Engine_Api::_()->authorization()->context;  
      $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

      $auth_keys = array(
       'view' => 'everyone',
       'comment' => 'registered',
      );
      
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
        
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($education, $role, $auth_key, ($i <= $authMax));
        }
      }

      
      // Add activity
      $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $education, 'education_new');
      if ($action != null)
      {
        Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $education);
      }

      
      // Commit
      $db->commit();
      
      return $this->_redirectCustom($education);

    }

    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }

  }

  public function editAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->education = $education = Engine_Api::_()->core()->getSubject('education');
    
    if( !$this->_helper->requireAuth()->setAuthParams($education, null, 'edit')->isValid())
    {
      return $this->_forward('requireauth', 'error', 'core');
    }

    // Get navigation
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('education_main');

    $this->view->form = $form = new Education_Form_Edit(array(
      'item' => $education
    ));

    $form->populate($education->toArray());

    $auth = Engine_Api::_()->authorization()->context;
    $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
    $auth_keys = array(
     'view' => 'everyone',
     'comment' => 'registered',
    );
    
    // Save education entry
    if( !$this->getRequest()->isPost() )
    {

      // prepare tags
      $educationTags = $education->tags()->getTagMaps();
      
      $tagString = '';
      foreach( $educationTags as $tagmap )
      {
        if( $tagString !== '' ) $tagString .= ', ';
        $tagString .= $tagmap->getTag()->getTitle();
      }

      $this->view->tagNamePrepared = $tagString;
      $form->keywords->setValue($tagString);
      
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_field = 'auth_'.$auth_key;
        
        foreach( $roles as $i => $role )
        {
          if (isset($form->$auth_field->options[$role]) && 1 === $auth->isAllowed($education, $role, $auth_key))
          {
            $form->$auth_field->setValue($role);
          }
        }
      }
      
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }


    // Process

    // handle save for tags
    $values = $form->getValues();
    $tags = preg_split('/[,]+/', $values['keywords']);
    $tags = array_filter(array_map("trim", $tags));

    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try
    {
      $education->setFromArray($values);
      $education->modified_date = date('Y-m-d H:i:s');

      $education->tags()->setTagMaps($viewer, $tags);
      $education->save();

      // Set photo
      if( !empty($values['photo']) ) {
        $education->setPhoto($form->photo);
      }      
    
      // Save custom fields
      $customfieldform = $form->getSubForm('customField');
      $customfieldform->setItem($education);
      $customfieldform->saveValues();

      // CREATE AUTH STUFF HERE
      $values = $form->getValues();
      
      // CREATE AUTH STUFF HERE
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
          
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($education, $role, $auth_key, ($i <= $authMax));
        }
      }
      
      $db->commit();


      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
      $form->addNotice($savedChangesNotice);
      $customfieldform->removeElement('submit');
      
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
  }
  


  public function deleteAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->education = $education = Engine_Api::_()->core()->getSubject('education');

    if( !$this->_helper->requireAuth()->setAuthParams($education, null, 'delete')->isValid()) {
      return;
    }

    // Get navigation
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_main');
    
    if( $this->getRequest()->isPost() && $this->getRequest()->getPost('confirm') == true )
    {
      $education->delete();
      return $this->_helper->redirector->gotoRoute(array('action'=>'manage'), 'education_general', true);
    }
  }

  public function tagsAction()
  {
    
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->form = $form = new Education_Form_Search();
    $form->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action'=>'browse'),'education_general',true));           
    // Get navigation
    $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_main');

    // Get quick navigation
    $this->view->quickNavigation = $quickNavigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('education_quick'); 
    
    $this->view->tags = $tags = Engine_Api::_()->education()->getPopularTags(array('limit' => 999, 'order' => 'text'));
  }


  
  
}

